import axios from "axios";
import { ElLoading, ElMessage } from "element-plus";
import { getToken } from "./token";
import router from "@/router";
import { useUserStore } from "@/stores/user";
import pinia from "@/stores/pinia";
const userStore = useUserStore(pinia)
// 成功的响应码
const RESPONSE_CODE = {
  success: 1000,
  reLogin: 3001
}


let loadingRequestCount = 0
let loadingInstance
const showLoading = () => {
  if (loadingRequestCount === 0) {
    loadingInstance = ElLoading.service({ target: '#app' })
  }
  loadingRequestCount += 1
}
const hideLoading = () => {
  if (loadingRequestCount <= 0) return
  loadingRequestCount -= 1
  if (loadingRequestCount === 0) {
    // nextTick(() => {
    loadingInstance.close()
    // })
  }
}


const instance = axios.create({
    baseURL: '/dev-api',
    timeout:5000
})

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  showLoading()
  if (getToken()) {
    config.headers["Authorization"] = "Bearer " + getToken();
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  hideLoading()
  const { data: resp } = response
  const { code, data, msg } = resp
  
  if (code === RESPONSE_CODE.success) {
    return resp
  }
  if (code === RESPONSE_CODE.reLogin) {
    // ElMessage.error(msg)
    userStore.logoutLocal()
    router.push('/login')
  } 
    return Promise.reject(new Error(msg));

  
}, function (error) {
  hideLoading()
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  return Promise.reject(error);
})

export default instance